package com.design.marketPrj.application.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController extends BaseController{

    @RequestMapping("/login")
//    @ResponseBody
    public String login(String username, String password, Model model){
        if(username==null&&password==null){
            model.addAttribute("msg","");
            return "login";
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        Subject currentUser = SecurityUtils.getSubject();
        try {
            //主体提交登录请求到SecurityManager
            currentUser.login(token);
            System.out.println("登录成功");
            model.addAttribute("user",getUser());
            return "redirect:product/index";
        }catch (IncorrectCredentialsException ice){
            model.addAttribute("msg","密码不正确");
            token.clear();
            return "login";
        }catch(UnknownAccountException uae){
            model.addAttribute("msg","账号不存在");
            token.clear();
            return "login";
        }catch(AuthenticationException ae){
            model.addAttribute("msg","状态不正常");
            token.clear();
            return "login";
        }
    }



}
